package com.easycarebn.main.fragment;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.easycarebn.main.utils.IResult;
import com.easycarebn.main.utils.Utils;
import com.easycarebn.main.utils.ViewmoreDetailt;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.controller.SuggestNameType;
import com.easycarebn.request.data.CommentsResponse;
import com.easycarebn.request.data.ContactInfoResponse;
import com.easycarebn.request.data.DoctorDetail;
import com.easycarebn.request.data.DoctorDetail.Address;
import com.easycarebn.request.data.DoctorScheduleResponse;
import com.easycarebn.request.data.FavoriteResponse;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.squareup.picasso.Picasso;
import com.timbacsi.main.DetailtActivity;
import com.timbacsi.main.EasyCareApplication;
import com.timbacsi.main.R;

public class FragmentDrDetailt extends Fragment implements IResult {

	private View mView;
	private static FragmentDrDetailt fragment = null;
	private IResult callIResult;

	private TextView tvDrName;
	private TextView lblChucvu;
	private TextView lblDesc;

	private TextView tvDrChuyenKhoa;
	private TextView tvDrPosition;
	private TextView tvRoomAddress;
	private RatingBar rb_dr;
	private ImageView imgDrAvatar;
	private TextView tvDrProfile;
	private TextView lblReadMore;

	private TextView tvDrWorkPlace;
	private TextView tvDrLstChuyenKhoa;
	private TextView tvDrAssociate;
	private TextView tvDrDegree;
	private TextView tv_dr_clinic_name;
	private View viewSchedule;
	private ScrollView mScrollView1;

	private Button btnThongchitiet;
	private Button btnDsbacsi;

	private Button btnNhanxetdg;
	private Button btnGuicmnt;
	private String phone = Utils.phone;

	private LinearLayout lineSendSms;
	private LinearLayout lineGoneAll;
	private LinearLayout lineInfodoctor;
	private LinearLayout lineProfile;

	private LinearLayout linePhongkham;

	private LinearLayout lineLike;

	private ImageView mBtnLike;
	private ImageView btnSendEmail;

	private DoctorDetail mDoctor;
	private LinearLayout lineMeta;
	private String mDataBooking;

	private int mServiceType;
	private boolean mIsFavorite;
	private String mToken;
	private int mDoctorId;
	private EasyCareApplication mApplication;

	public static FragmentDrDetailt newInstance(String title) {
		if (fragment == null)
			fragment = new FragmentDrDetailt();

		return fragment;
	}

	public void update() {// call when login success
		UserResponse user = Utils.getUserLogin(getActivity());
		if (user == null) {
			mToken = null;
			mBtnLike.setVisibility(View.GONE);
			btnSendEmail.setVisibility(View.GONE);
		} else {
			mToken = user.getToken();
			mBtnLike.setVisibility(View.VISIBLE);
			btnSendEmail.setVisibility(View.VISIBLE);
		}

	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		if (activity instanceof IResult) {
			callIResult = (IResult) activity;
		}
		mApplication = (EasyCareApplication) activity.getApplicationContext();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_listdr, null);
		mBtnLike = (ImageView) mView.findViewById(R.id.btnLike);
		btnSendEmail = (ImageView) mView.findViewById(R.id.btnSendEmail);
		lineSendSms = (LinearLayout) mView.findViewById(R.id.lineSendSMS);
		lineLike = (LinearLayout) mView.findViewById(R.id.lineLike);
		return mView;
	}

	@Override
	public void onResume() {
		super.onResume();
		update();
		mApplication.setmCommentsResponse(null);
		displayDoctor(mDoctorId);
		loadComments(mDoctorId);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		tvDrName = (TextView) mView.findViewById(R.id.tv_dr_name);
		mScrollView1 = (ScrollView) mView.findViewById(R.id.scrollView1);

		lblChucvu = (TextView) mView.findViewById(R.id.lblChucvu);
		lineInfodoctor = (LinearLayout) mView.findViewById(R.id.lineInfodoctor);
		lineProfile = (LinearLayout) mView.findViewById(R.id.lineProfile);

		lineInfodoctor.setVisibility(View.GONE);

		linePhongkham = (LinearLayout) mView.findViewById(R.id.linePhongkham);
		linePhongkham.setVisibility(View.GONE);

		lineMeta = (LinearLayout) mView.findViewById(R.id.lineMeta);
		lineMeta.setVisibility(View.GONE);

		lineGoneAll = (LinearLayout) mView.findViewById(R.id.lineGoneAll);

		tvDrChuyenKhoa = (TextView) mView.findViewById(R.id.tv_dr_chuyen_khoa);
		tvRoomAddress = (TextView) mView
				.findViewById(R.id.tv_dr_clininic_address);
		tv_dr_clinic_name = (TextView) mView
				.findViewById(R.id.tv_dr_clinic_name);

		tvDrPosition = (TextView) mView.findViewById(R.id.tv_dr_position);

		imgDrAvatar = (ImageView) mView.findViewById(R.id.img_dr_avatar);
		rb_dr = (RatingBar) mView.findViewById(R.id.rb_dr_rating);
		tvDrWorkPlace = (TextView) mView.findViewById(R.id.tv_work_place);
		tvDrAssociate = (TextView) mView.findViewById(R.id.tv_associate);
		tvDrDegree = (TextView) mView.findViewById(R.id.tv_dr_degree);
		tvDrLstChuyenKhoa = (TextView) mView.findViewById(R.id.tv_dr_lst_ck);
		lblReadMore = (TextView) mView.findViewById(R.id.lblReadMore);
		tvDrProfile = (TextView) mView.findViewById(R.id.tv_dr_profile);

		viewSchedule = mView.findViewById(R.id.view_schedule);
		viewSchedule.setVisibility(View.GONE);
		lineGoneAll.setVisibility(View.INVISIBLE);

		Utils.setOnTouchHideKeyboard(getActivity(), mView);
		Intent data = getActivity().getIntent();
		if (data == null) {
			return;
		}

		mDoctorId = data.getIntExtra(Utils.KEY_DOCTOR_ID, -1);
		mServiceType = data.getIntExtra(Utils.KEY_SERVICE_TYPE, -1);
		callIResult.onDisplay(Utils.TASK_CHILD, "");

		btnNhanxetdg = (Button) mView.findViewById(R.id.btnNhanxetdg);
		btnGuicmnt = (Button) mView.findViewById(R.id.btnSendCmt);

		btnGuicmnt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				formSendComment();
				mScrollView1.fullScroll(View.FOCUS_DOWN);
			}
		});

		btnNhanxetdg.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				formListCommment();
			}
		});
		lineSendSms.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int reply_for_notification_id = 0;
				Utils.sendMessagesToDocter(getActivity(), mToken, mDoctor,
						reply_for_notification_id);
			}
		});

		TextView tvBookingNearDate = (TextView) mView
				.findViewById(R.id.tv_booking_neardate);
		ContactInfoResponse dataCt = Utils.getContactInfo(getActivity());
		if (dataCt != null && dataCt.getContactInfo() != null)
			phone = dataCt.getContactInfo().getEasycare_phone().toString();

		tvBookingNearDate.setText(Html.fromHtml(getResources().getString(
				R.string.so_dien_thoai_ho_tro_ps,
				Utils.setTextcolorHtml("<br>" + phone, "#00a3e0"))));
		tvBookingNearDate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.callPhone(phone, (Activity) getActivity());
			}
		});

		Button btnDatlichtruoc = (Button) mView
				.findViewById(R.id.btnDatlichtruoc);
		btnDatlichtruoc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Utils.showDatlichtruoc(getActivity(), mDoctor);

			}
		});

		btnDsbacsi = (Button) mView.findViewById(R.id.btnDsbacsi);
		btnThongchitiet = (Button) mView.findViewById(R.id.btnttChitiet);
		btnThongchitiet.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showProfileDoctor();
			}
		});

		btnDsbacsi.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				btnThongchitiet.setSelected(false);
				btnDsbacsi.setSelected(true);
				getActivity()
						.getSupportFragmentManager()
						.beginTransaction()
						.replace(R.id.fragment_list_doctor,
								FragmentListDoctor.newInstance(""))
						.addToBackStack(null).commit();
			}
		});

		// displayDoctor(doctorId);

	}

	public void formListCommment() {
		btnGuicmnt.setSelected(false);
		btnNhanxetdg.setSelected(true);
		if (getActivity() == null)
			return;
		
			getActivity()
					.getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fragment_comment,
							FragmentComment.newInstance(""), "TAG_COMMENT")
					.addToBackStack(null).commit();
	}

	public void formSendComment() {
		if (getActivity() == null)
			return;
			getActivity()
					.getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fragment_comment,
							FragmentSendComment.newInstance(""))
					.addToBackStack(null).commit();
		btnGuicmnt.setSelected(true);
		btnNhanxetdg.setSelected(false);
	}

	public void showProfileDoctor() {
		btnThongchitiet.setSelected(true);
		btnDsbacsi.setSelected(false);
		if (!getActivity().isFinishing())
			getActivity()
					.getSupportFragmentManager()
					.beginTransaction()
					.replace(R.id.fragment_list_doctor,
							FragmentAboutDoctor.newInstance(""))
					.addToBackStack(null).commit();

	}

	private void displayDoctor(final int doctorId) {
		if (doctorId == -1 || mServiceType == -1) {
			return;
		}

		DetailtActivity.loadding.setVisibility(View.VISIBLE);
		ServerController.getInstance(getActivity()).requestGetDoctorDetail(
				doctorId, mServiceType, mToken, new OnRequest<DoctorDetail>() {

					@Override
					public void onSuccess(final DoctorDetail data) {
						if (getActivity() == null)
							return;

						if (data == null) {
							return;
						}
						mDoctor = data;

						if (mServiceType == SuggestNameType.CLINIC.getCode()
								&& data.getListdoctor().size() > 0) {
							if (!data.getProfile().isEmpty()) {
								showProfileDoctor();
								linePhongkham.setVisibility(View.VISIBLE);
								lineProfile.setVisibility(View.GONE);
							} else {
								btnThongchitiet.setVisibility(View.GONE);
								linePhongkham.setVisibility(View.GONE);
								lineProfile.setVisibility(View.GONE);
							}

						} else {
							linePhongkham.setVisibility(View.GONE);
							lineProfile.setVisibility(View.VISIBLE);
						}

						tvDrName.setText(data.getName());
						Picasso.with(getActivity()).load(data.getAvatar())
								.resize(Utils.IMG_WIDHT, Utils.IMG_HEIGHT)
								.placeholder(R.drawable.avata)
								.error(R.drawable.avata).into(imgDrAvatar);
						if (data.getPosition() == null
								|| data.getPosition().isEmpty()) {
							tvDrPosition.setVisibility(View.GONE);
						} else {
							tvDrPosition.setText(Html.fromHtml(data
									.getPosition()));
						}

						if (mServiceType == SuggestNameType.DOCTOR.getCode()) {
							lineInfodoctor.setVisibility(View.VISIBLE);
							if (data.getAddress().isEmpty()) {
								Utils.setTextEmpty(tvRoomAddress, getActivity());
							} else {
								// tvRoomAddress.setText(Html.fromHtml(data
								// .getAddress()));
								//
								Utils.setAddress(tvRoomAddress,
										data.getList_address());
							}

							tv_dr_clinic_name.setVisibility(View.VISIBLE);
							if (data.getClinicname_default().isEmpty()) {
								Utils.setTextEmpty(tv_dr_clinic_name,
										getActivity());
							} else {
								tv_dr_clinic_name.setText(data
										.getClinicname_default());
							}
						} else {
							lineInfodoctor.setVisibility(View.GONE);
							Utils.setAddress(tvRoomAddress,
									data.getList_address());
						}

						lblDesc = (TextView) mView.findViewById(R.id.lblDesc);
						if (data.getRating() == 0) {
							lblDesc.setVisibility(View.VISIBLE);
							rb_dr.setVisibility(View.GONE);
						} else {
							lblDesc.setVisibility(View.GONE);
							rb_dr.setRating(data.getRating());
						}

						if (mServiceType == SuggestNameType.DOCTOR.getCode()
								&& data.getSpeciality() != null
								&& !data.getSpeciality().isEmpty()) {
							tvDrChuyenKhoa.setText(String.format(
									getActivity().getResources().getString(
											R.string.chuyen_khoa_bs), data
											.getSpeciality().get(0)));
						} else {
							if (data.getClinictype() != null
									&& data.getClinictype().size() > 0) {
								tvDrChuyenKhoa.setText(data.getClinictype()
										.get(0));
							} else {
								tvDrChuyenKhoa.setVisibility(View.GONE);
							}
						}

						if (data.getShort_content().isEmpty()) {
							Utils.setTextEmpty(tvDrProfile, getActivity());
						} else {
							tvDrProfile.setText(Html.fromHtml(data
									.getShort_content()));
						}

						if (!TextUtils.isEmpty(data.getProfile())) {

							lblReadMore
									.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View v) {
											new ViewmoreDetailt(getActivity(),
													data.getProfile())
													.getDialogReadMore();

										}
									});
						} else {
							Utils.setTextEmpty(tvDrProfile, getActivity());
							lblReadMore.setVisibility(View.GONE);
						}

						if (!data.getAssociations().isEmpty()) {
							tvDrAssociate.setText(data.getAssociations());
						} else {
							Utils.setTextEmpty(tvDrAssociate, getActivity());
						}
						if (!data.getPlaceofworks().isEmpty()) {
							tvDrWorkPlace.setText(data.getPlaceofworks());
						} else {
							Utils.setTextEmpty(tvDrWorkPlace, getActivity());

						}
						if (!data.getSpecialities().isEmpty()) {
							tvDrLstChuyenKhoa.setText(data.getSpecialities());
						} else {
							Utils.setTextEmpty(tvDrLstChuyenKhoa, getActivity());
						}
						if (!data.getDegrees().isEmpty()) {
							tvDrDegree.setText(data.getDegrees());
						} else {
							Utils.setTextEmpty(tvDrDegree, getActivity());
						}

						if (!data.getDegrees().isEmpty()) {
							lblChucvu.setText(Html.fromHtml(data.getPosition()));
						} else {
							Utils.setTextEmpty(lblChucvu, getActivity());
						}

						if (data.getFavorite() == 0) {
							mBtnLike.setImageResource(R.drawable.ic_liked);
							mIsFavorite = true;
						} else {
							mBtnLike.setImageResource(R.drawable.ic_unlike);
							mIsFavorite = false;
						}
						lineLike.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								if (!mIsFavorite) {
									Utils.showMessage(
											getActivity(),
											getResources().getString(
													R.string.bo_yeu_thich), v);
								} else {
									Utils.showMessage(
											getActivity(),
											getResources().getString(
													R.string.yeu_thich), v);
								}
								actionFavorite(data);
							}
						});

						if (data.getBooking() != null
								&& !TextUtils.isEmpty(data.getBooking()
										.getNeardate())) {
							getBooking(data);
							lineMeta.setVisibility(View.GONE);
							tvDrName.setEnabled(false);
						} else {
							DetailtActivity.loadding.setVisibility(View.GONE);

							lineGoneAll.setVisibility(View.VISIBLE);
							lineMeta.setVisibility(View.VISIBLE);
							tvDrName.setEnabled(true);
							viewSchedule.setVisibility(View.GONE);
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						DetailtActivity.loadding.setVisibility(View.GONE);
						if (errorCode == 0) {
							Utils.onResumeRequest(getActivity(), mView,
									new IResult() {
										@Override
										public void onDisplay(int arg1,
												String arg2) {
											displayDoctor(doctorId);
										}
									});

						}
					}
				});

	}

	public void getBooking(final DoctorDetail data) {
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity())
				.requestSearchDoctorSchedule(data.getDoctorId(),
						data.getBooking().getNeardate(),
						new OnRequest<DoctorScheduleResponse>() {

							@Override
							public void onSuccess(
									DoctorScheduleResponse schedule) {
								DetailtActivity.loadding
										.setVisibility(View.GONE);
								Utils.disableEnableControls(true, mView);
								lineGoneAll.setVisibility(View.VISIBLE);
								if (data != null && schedule.getItems() != null
										&& !schedule.getItems().isEmpty()) {
									viewSchedule.setVisibility(View.VISIBLE);
									new FragmentCalender(getActivity(),
											FragmentDrDetailt.this, data
													.getDoctorId(), schedule
													.getItems(), schedule,
											viewSchedule, null).init();
								} else {
									lineMeta.setVisibility(View.VISIBLE);
								}
							}

							@Override
							public void onError(int errorCode, String message) {
								Utils.disableEnableControls(true, mView);
								DetailtActivity.loadding
										.setVisibility(View.GONE);

							}

						});

	}
	@Override
	public void onPause() {
		super.onPause();
		RequestQueue queue = Volley.newRequestQueue(getActivity());
		queue.cancelAll(new RequestQueue.RequestFilter() {
		    @Override
		        public boolean apply(Request<?> request) {
		            return true;
		        }
		    });
	}

	public void actionFavorite(DoctorDetail data) {
		Utils.disableEnableControls(false, lineLike);
		ServerController.getInstance(getActivity()).requestFavorite(
				data.getDoctorId(), mToken, mIsFavorite,
				new OnRequest<FavoriteResponse>() {

					@Override
					public void onSuccess(FavoriteResponse data) {
						Utils.disableEnableControls(true, lineLike);
						if (data.getCode() != 200) {
							return;
						}
						if (mIsFavorite) {
							mBtnLike.setImageResource(R.drawable.ic_unlike);
							Log.d("unliked", "unliked");
							mIsFavorite = false;
						} else {
							Log.d("liked", "liked");
							mBtnLike.setImageResource(R.drawable.ic_liked);
							mIsFavorite = true;
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						Utils.disableEnableControls(true, lineLike);
					}
				});

	}

	public DoctorDetail getCurrentDoctor() {
		return mDoctor;
	}

	// public CommentsResponse getDoctorComments() {
	// return mDoctorComments;
	// }

	public ArrayList<Address> getListAddresses() {
		if (mDoctor == null)
			return null;
		return mDoctor.getList_address();
	}

	private void loadComments(int doctorId) {
		Log.d("loadComments", "loadComments");
		if (doctorId == -1) {
			return;
		}
		ServerController.getInstance(getActivity()).requestGetDoctorComments(
				doctorId, 1, Utils.numberOfRecord,
				new OnRequest<CommentsResponse>() {

					@Override
					public void onSuccess(CommentsResponse data) {
						// mDoctorComments = data;

						mApplication.setmCommentsResponse(data);

						// Log.d("Binhluan",
						// mDoctorComments.getItems().get(0).getComment());
						if (data != null && data.getItems() != null
								&& data.getItems().size() > 0) {
							formListCommment();
						} else {
							formSendComment();

						}
					}

					@Override
					public void onError(int errorCode, String message) {
						// mDoctorComments = null;
					}
				});
	}

	@Override
	public void onDisplay(int code, String data) {
		if (code == Utils.SELECT_TIME_BOOKING) {
			mDataBooking = data;
			UserResponse userResponse = Utils.getUserLogin(getActivity());
			if (userResponse == null) {
				Utils.intentToDetailt(getActivity(), Utils.LOGIN_BOOKING);
			} else {
				Utils.gotoBooking(getActivity(), data, mServiceType);
			}

		}
	}

	public String getDataBooking() {
		return mDataBooking;
	}

}
